import { useState, useCallback, useRef } from 'react';
import { message } from 'antd';
import { Student, getStudentList, searchStudents, deleteStudent, joinGroup, exitGroup } from '@/utils/api/student/student';

interface UseStudentDataProps {
    pageSize: number;
}

export const useStudentData = ({ pageSize }: UseStudentDataProps) => {
    const [students, setStudents] = useState<Student[]>([]);
    const [total, setTotal] = useState<number>(0);
    const [pages, setPages] = useState<number>(0);
    const [loading, setLoading] = useState<boolean>(false);
    const [searchParams, setSearchParams] = useState<any>({});

    const abortControllerRef = useRef<AbortController | null>(null);

    // 获取学生列表
    const fetchStudents = useCallback(async (pageNum: number = 1, pageSize: number = 10, params: any = {}) => {
        // 中断之前的请求
        if (abortControllerRef.current) {
            abortControllerRef.current.abort();
        }

        // 创建新的AbortController
        const controller = new AbortController();
        abortControllerRef.current = controller;

        try {
            setLoading(true);

            // 判断是否有搜索参数，决定使用哪个API
            const hasSearchParams = Object.keys(params).length > 0;

            let response;
            if (hasSearchParams) {
                // 使用搜索API，参数放在请求体中
                const requestData = {
                    pageNum: pageNum,
                    pageSize: pageSize,
                    ...params
                };
                response = await searchStudents(requestData, { signal: controller.signal });
            } else {
                // 使用普通获取列表API，参数放在URL中
                const requestParams = {
                    pageNum: pageNum,
                    pageSize: pageSize,
                    ...params
                };
                response = await getStudentList(requestParams, { signal: controller.signal });
            }

            // 检查请求是否被中止
            if (controller.signal.aborted) {
                return;
            }

            const data = response.data;
            const list = data.list.map((student: Student) => ({
                ...student,
                createTime: student.createTime
            }));

            setStudents(list);
            setTotal(data.total);
            setPages(data.pages);

            return {
                current: pageNum,
                pageSize
            };
        } catch (error: any) {
            // 如果是中止请求的错误，不显示错误信息
            if (error.name === 'AbortError') {
                console.log('请求被中止');
                return;
            }
            console.error('获取学生列表失败:', error);
            throw error;
        } finally {
            setLoading(false);
        }
    }, []);

    // 处理搜索
    const handleSearch = useCallback((params: any) => {
        // 转换参数格式
        const searchData = {
            ...params,
            sex: params.sex !== undefined ? Number(params.sex) : undefined,
            age: params.age ? Number(params.age) : undefined
        };

        // 移除空值
        Object.keys(searchData).forEach(key => {
            if (searchData[key] === undefined || searchData[key] === '') {
                delete searchData[key];
            }
        });

        setSearchParams(searchData);
        return fetchStudents(1, pageSize, searchData);
    }, [fetchStudents, pageSize]);

    // 处理重置
    const handleReset = useCallback(() => {
        setSearchParams({});
        return fetchStudents(1, pageSize);
    }, [fetchStudents, pageSize]);

    // 处理删除学生
    const handleDelete = useCallback(async (id: number, currentPage: number, studentsCount: number) => {
        try {
            setLoading(true);
            await deleteStudent(id);
            message.success("删除成功");

            const isLastItemOnPage = studentsCount === 1;

            if (isLastItemOnPage && currentPage > 1) {
                return fetchStudents(currentPage - 1, pageSize, searchParams);
            } else {
                return fetchStudents(currentPage, pageSize, searchParams);
            }
        } catch (error) {
            console.error("删除失败:", error);
            throw error;
        } finally {
            setLoading(false);
        }
    }, [fetchStudents, pageSize, searchParams]);

    // 处理加入小组
    const handleJoinGroup = useCallback(async (studentId: number, groupId: number, currentPage: number) => {
        try {
            setLoading(true);
            const response = await joinGroup(studentId, groupId);

            if (response.code === 200) {
                message.success('加入小组成功');
                return fetchStudents(currentPage, pageSize, searchParams);
            } else {
                message.error(response.data.msg || '加入小组失败');
                throw new Error(response.data.msg || '加入小组失败');
            }
        } catch (error) {
            console.error('加入小组失败:', error);
            throw error;
        } finally {
            setLoading(false);
        }
    }, [fetchStudents, pageSize, searchParams]);

    // 处理退出小组
    const handleExitGroup = useCallback(async (studentId: number, groupId: number, currentPage: number) => {
        try {
            setLoading(true);
            await exitGroup(studentId, groupId);
            message.success("退出小组成功");
            return fetchStudents(currentPage, pageSize, searchParams);
        } catch (error) {
            console.error("退出小组失败:", error);
            throw error;
        } finally {
            setLoading(false);
        }
    }, [fetchStudents, pageSize, searchParams]);

    return {
        students,
        total,
        pages,
        loading,
        searchParams,
        fetchStudents,
        handleSearch,
        handleReset,
        handleDelete,
        handleJoinGroup,
        handleExitGroup,
        setLoading
    };
};